package com.itheima.app.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;

@Component //放入容器
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 拦截方法
     * 代码是需要测试的
     *  1.内测
     *  2.UAT测试(测试部门测试)
     *  3.修改 再测试
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //1.获得到token
            String token = request.getHeader("Authorization");
            if(StrUtil.isEmpty(token)){
                response.setStatus(401);//前端和后台规定好的401 权限不足的状态
                return false;
            }

            //2.校验redis中的token
            Boolean flag = stringRedisTemplate.hasKey(ConstantUtil.USER_TOKEN + token);
            if(!flag){
                response.setStatus(401);//前端和后台规定好的401 权限不足的状态
                return false;
            }

            //3.解析token
            Map map = JwtUtil.parseToken(token);
            //map 转换成 User
            User user = BeanUtil.mapToBean(map, User.class, true);
            if(user == null){
                response.setStatus(401);//前端和后台规定好的401 权限不足的状态
                return false;
            }

            //4.绑定
            UserHolder.set(user);
            //5.续期
            stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token , "1" , Duration.ofDays(30) );
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(401);//前端和后台规定好的401 权限不足的状态
            return false;
        }

        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
